//
//  SchoolViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/21.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "SchoolViewController.h"
#import "CollegeDetailViewController.h"
#import "SchoolCollectionViewCell.h"
#import "SchoolCLOViewController.h"
#import "AllHeader.h"
#import "SchoolHeadView.h"
#import <AFNetworking.h>
#import "AreaModel.h"
#import "SpaceModel.h"

#define ssURL @"http://arts1.dlab.com.cn/app/space"

@interface SchoolViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SchoolHeadViewDelegate>

// 横向滑动视图
@property (nonatomic, strong) SchoolHeadView *schoolheadView;

// 存储数据
@property (nonatomic, strong) NSMutableArray *dataArr;

// 地区
@property (nonatomic, strong) AreaModel *area;



@end

@implementation SchoolViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    // Do any additional setup after loading the view.
    [self createCollectionView];
}

// 数据元的懒加载
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

//请求数据
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //请求参数
    NSDictionary *pardic = @{@"type":@"高校"};
    
    [manage POST:ssURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         // status 的值为1时，操作成功，可以使用数据
         NSInteger status = [dic[@"status"] integerValue];
         
         NSLog(@"高校请求到的数据 %@ ",dic);
         
         if (status == 1) {
             // type的值为画室时代表的是画室的数据，其他的为高校的数据
             self.dataArr = nil;
             self.areaArr = nil;
             
             NSArray *listArr = dic[@"list"];
             for (NSDictionary *dict in listArr) {
                 SpaceModel *space = [[SpaceModel alloc] init];
                 [space setValuesForKeysWithDictionary:dict];
                 [self.dataArr addObject:space];
             }
         }

         dispatch_async(dispatch_get_main_queue(), ^{
             [_collectionView reloadData];
         });
         
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
    
}

// 创建滑动视图
- (void)createCollectionView{
    // 横向滑动的collectionview
    _schoolheadView = [[SchoolHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (SCREEN_WIDTH - 5 * 10) / 4  + 10)];
    _schoolheadView.dataArr = _areaArr;
    _schoolheadView.delegate = self;
    
    // 纵向滑动的视图collectionview
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //两个item之间相距5
    layout.minimumInteritemSpacing = 5;
    //   layout.minimumLineSpacing = 5;
    // 创建collectionview
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, (SCREEN_WIDTH - 5 * 10) /  4 + 10, SCREEN_WIDTH, self.view.height - (SCREEN_WIDTH - 5 * 10) / 4  - 10) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.alwaysBounceVertical = YES;
    // 注册cell
    [_collectionView registerClass:[SchoolCollectionViewCell class] forCellWithReuseIdentifier:@"schoolcollectioncell"];
    
    // 加载横向和纵向滑动的视图
    [self.view addSubview:_collectionView];
    [self.view addSubview:_schoolheadView];
}

#pragma mark -- SchoolHeadViewDelegate
- (void)changeSchoolByArea:(AreaModel *)area{
    _area = area;
    [self changeData];
}

// 点击不同地区之后，更换下面院校列表的数据
- (void)changeData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //请求参数
    NSDictionary *pardic = @{@"type":@"高校"};
    if (_area && ![_area.place isEqualToString:@"九大美院"] ) {
        pardic = @{@"type":@"高校",@"area":_area.place};
    }
    
    [manage POST:ssURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         // status 的值为1时，操作成功，可以使用数据
         NSInteger status = [dic[@"status"] integerValue];
         
         NSLog(@"高校，画室请求道的数据 %@ ",dic);
         
         if (status == 1) {
             self.dataArr = nil;
             
             NSArray *listArr = dic[@"list"];
             for (NSDictionary *dict in listArr) {
                 SpaceModel *space = [[SpaceModel alloc] init];
                 [space setValuesForKeysWithDictionary:dict];
                 [self.dataArr addObject:space];
             }
            // 在主线中，刷新数据，展示数据
         dispatch_async(dispatch_get_main_queue(), ^{
             [_collectionView reloadData];
         });
         
         }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];

}

#pragma mark ---- UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArr.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_WIDTH - 20, 80);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        SchoolCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"schoolcollectioncell" forIndexPath:indexPath];
    SpaceModel *school = (SpaceModel *)_dataArr[indexPath.row];
    cell.school = school;
        return cell;
    
}

// 点击事件，进入相应的详情页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SpaceModel *model = _dataArr[indexPath.row];
    [self enterCollegeDetailView:model.space_Id];
}

- (void)enterCollegeDetailView:(NSString *)ID{
    UIResponder *responder = [self.view nextResponder];
    while (responder) {
        if ([responder isKindOfClass:[SchoolCLOViewController class]]) {
            SchoolCLOViewController *schVC = (SchoolCLOViewController *)responder;
             CollegeDetailViewController *collegeDVC = [[CollegeDetailViewController alloc] init];
            collegeDVC.ID = ID;
            [schVC.navigationController pushViewController:collegeDVC animated:YES];
        }
        responder = [responder nextResponder];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
